package kingwing.dc.core.sevice.quartz.view;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import kingwing.dc.core.model.Infos;
import kingwing.dc.core.model.JobTimeRule;
import kingwing.dc.core.model.Rule;
import kingwing.dc.core.orm.hibernate.CommonHibernateDao;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.exception.NoneLoginException;
import com.bstek.bdf2.core.orm.hibernate.ISessionCallback;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Page;

@Component
public class TimedTaskPR {
	
	@Resource(name=CommonHibernateDao.BEAN_ID)
	private CommonHibernateDao commonHibernateDao;
	

	/**
	 * 依据任务id获取站点
	 * @param id
	 * @return
	 */
	@DataProvider
	public void getRules(Page<Rule> page,String id){
		
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new NoneLoginException("登陆超时，请登录！");
		}
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Rule.class);
		
		if (StringUtils.isNotBlank(id)) {
			detachedCriteria.add(Restrictions.and( Restrictions.eq("jobTimeRuleID", id),
					Restrictions.eq("createUserId", user.getUsername())));
		}
		
		this.commonHibernateDao.pagingQuery(page, detachedCriteria);
		
	}
	
	/**
	 * 保存任务
	 * @param sobTimeRules
	 */
	@Transactional
	@DataResolver
	public String jobTimeRuleCRUD(Collection<JobTimeRule> jobTimeRules){
		
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new NoneLoginException("登陆超时，请登录！");
		}
		
		if (jobTimeRules==null) {
			return "传入的数据为空！";
		}
		
		for (JobTimeRule jobTimeRule : jobTimeRules) {
			
			EntityState state = EntityUtils.getState(jobTimeRule);
			
			if (state.equals(EntityState.NEW) && !isExistJobTimeRule(jobTimeRule.getJobName(), user.getUsername())) {
				this.commonHibernateDao.save(jobTimeRule);
				return "添加成功！";
			}else if (state.equals(EntityState.MODIFIED)) {
				this.commonHibernateDao.update(jobTimeRule);
				return "修改成功！";
			}else if (state.equals(EntityState.DELETED)) {
				this.deleteSiteForJobID(jobTimeRule.getId());
				this.commonHibernateDao.delete(jobTimeRule);
				return "删除成功！";
			}
			
		}
		
		return null;
		
	}
	
	/**
	 * 分页获取任务
	 * @param page
	 */
	@DataProvider
	public void getJobTimeRulePage(Page<JobTimeRule> page){
		
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new NoneLoginException("登陆超时，请登录！");
		}
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(JobTimeRule.class);
		
		detachedCriteria.add(Restrictions.eq("createUserId", user.getUsername()));
		
		
		this.commonHibernateDao.pagingQuery(page, detachedCriteria);
	}
	
	/**
	 * 获取所有的规则
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@DataProvider
	public Collection<Rule>  getRule(){
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Rule.class);
		detachedCriteria.add(Restrictions.isNull("jobTimeRuleID"));
		detachedCriteria.add(Restrictions.eq("createUserId", ContextHolder.getLoginUserName()));
		return (Collection<Rule>) this.commonHibernateDao.query(detachedCriteria);
	}
	
	/**
	 * 获取任务
	 * @param page
	 */
	@SuppressWarnings("unchecked")
	@DataProvider
	public Collection<JobTimeRule> getJobTimeRule(){
		
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new NoneLoginException("登陆超时，请登录！");
		}
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(JobTimeRule.class);
		
		detachedCriteria.add(Restrictions.eq("createUserId", user.getUsername()));
		
		
		return (Collection<JobTimeRule>) this.commonHibernateDao.query( detachedCriteria);
	}
	
	/**
	 * 添加站点到任务中
	 * @param params
	 * @return
	 */
	@Transactional
	@Expose
	public String addSiteTojob(Collection<String> ids,String jobID){
		
		List<Rule> rules = new ArrayList<Rule>();
		
		for (String ruleID : ids) {
			Rule rule = this.commonHibernateDao.get(ruleID, Rule.class);
			
			if (jobID.equals(rule.getJobTimeRuleID())) {
//				return rule.getRuleName();
			}else{
				rules.add(rule);
			}
		}
		
		if (rules!=null&&rules.size()!=0) {
			for (Rule rule : rules) {
				rule.setJobTimeRuleID(jobID);
				this.commonHibernateDao.update(rule);
			}
		}
		
		return null;
	}
	
	/**
	 * 删除添加的站点
	 * @param ruleID
	 * @return
	 */
	@Transactional
	@Expose
	public String deleteSite(String ruleID){
		
		//DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Rule.class);
		
		Rule rule = this.commonHibernateDao.get(ruleID, Rule.class);
		
		rule.setJobTimeRuleID(null);
		
		this.commonHibernateDao.update(rule);
		
		return null;
	}
	
	/**
	 * 根据任务名和用户ID判断是否有重复任务存在
	 * @param jobName
	 * @param userName
	 * @return
	 */
	private boolean isExistJobTimeRule(String jobName,String userName){
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(JobTimeRule.class);
		
		if(StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(userName)){
			detachedCriteria.add(Restrictions.and(Restrictions.eq("jobName", jobName), 
					Restrictions.eq("createUserId", userName)));
			
			int count = this.commonHibernateDao.queryCount(detachedCriteria);
			
			if (count>0) {
				return true;
			}else{
				return false;
			}
		}else {
			return false;
		}
	}
	
	/**
	 * 获取任务站点采集信息
	 * 
	 * @param page
	 * @param rule
	 * @param taskTime
	 */
	@DataProvider
	public void getInfosPage(Page<Infos> page,Collection<Rule> rule,Date taskTime){
		
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Infos.class);
		Disjunction disjunction = Restrictions.disjunction();
		if (rule!=null&&rule.size()!=0) {
			for (Rule r : rule) {
				String ruleName = r.getRuleName();
				disjunction.add(Restrictions.eq("ruleName", ruleName));
				
			}
			detachedCriteria.add(disjunction);
			detachedCriteria.add(Restrictions.ge("createDate", taskTime));
			detachedCriteria.add(Restrictions.eq("createUserId", ContextHolder.getLoginUserName()));
			commonHibernateDao.pagingQuery(page, detachedCriteria);
		}
		
	}
	@SuppressWarnings("unchecked")
	@Transactional
	private void deleteSiteForJobID(String jobID){
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Rule.class);
		
		detachedCriteria.add(Restrictions.eq("jobTimeRuleID", jobID));
		
		List<Rule> rules = (List<Rule>) this.commonHibernateDao.query(detachedCriteria);
		
		if (rules!=null&&rules.size()!=0) {
			for (Rule rule : rules) {
				this.deleteSite(rule.getId());
			}
		}
		
		
	}
	
}
